package sort;

public class MergeSort implements ISort{

	private int[] arrTmp;
	private int arrSize;

	public void sort(int[] arr) {
		arrTmp = new int[arr.length];
		sort(arr, 0, arr.length - 1);
	}

	public void sort(int[] arr, int start, int end) {
		if (start == end) {
			return;
		}
		int mid = (start + end) / 2;
		sort(arr, start, mid);
		sort(arr, mid + 1, end);
		merge(arr, start, mid, mid + 1, end);
		for (int i = 0; i < arrSize; i++) {
			arr[start + i] = arrTmp[i];
		}
		arrSize = 0;
	}

	public void merge(int[] arr, int start1, int end1, int start2, int end2) {
		int i = start1, j = start2;
		while (i <= end1 && j <= end2) {
			if (arr[i] > arr[j]) {
				arrTmp[arrSize++] = arr[j++];
			} else {
				arrTmp[arrSize++] = arr[i++];
			}
		}
		if (j > end2) {
			for (int m = i; m <= end1; m++) {
				arrTmp[arrSize++] = arr[m];
			}
		} else if (i > end1) {
			for (int n = j; n <= end2; n++) {
				arrTmp[arrSize++] = arr[n];
			}
		}
	}

	public static void main(String[] args) {
		MergeSort mergeSort = new MergeSort();
		int arr[] = { 8, 4, 7, 9, 6, 3, 1, 2, 5 };
		mergeSort.sort(arr);
		ISort.printArr(arr);
	}

}
